package com.burningtower.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.burningtower.entity.Role;
import com.burningtower.entity.RoleResource;
import com.burningtower.mapper.RoleMapper;
import com.burningtower.service.IRoleResourceService;
import com.burningtower.service.IRoleService;
import com.burningtower.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author zhe
 * @since 2017-11-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private IRoleResourceService roleResourceService;

    @Override
    @Transactional
    public void grant(Long id, String resourceIds) {
        //获取新的授权列表resourceIds2
        String[] resourceIds1=resourceIds.split(",");
        List<Long> resourceIdNew=new ArrayList<>();
        for(String str:resourceIds1){
            resourceIdNew.add(Long.valueOf(str));
        }
        //获取旧的授权列表resourceIdList
        List<Long> resourceIdOld = roleResourceService.selectResourceIdListByRoleId(id);
        Iterator<Long> iterator=resourceIdOld.iterator();
        while (iterator.hasNext()){
            Long resourceId=iterator.next();
            if(!resourceIdNew.contains(resourceId)){//如果新的授权列表不包含旧的，则删除旧的
                roleResourceService.delete(new EntityWrapper<>(new RoleResource(id,resourceId)));
                iterator.remove();
            }
        }
        for(Long resourceId:resourceIdNew){
            if(!resourceIdOld.contains(resourceId)){//如果旧的列表不包含新的授权，则添加
                roleResourceService.insert(new RoleResource(id,resourceId));
            }
        }
    }

    @Override
    public TreeVo toVo(Role role) {
        TreeVo vo = new TreeVo();
        vo.setId(role.getId());
        vo.setText(role.getName());
        vo.setState("open");
        vo.setChecked(false);
        return vo;
    }
}
